package simpleeditor.controllers;

import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QTableWidget;

public abstract class TableController{
	
	protected QPushButton addButton,removeButton;
	protected QTableWidget table;
	
	public TableController(QTableWidget table,QPushButton addButton,QPushButton removeButton) {
		this.addButton=addButton;
		this.removeButton=removeButton;
		this.table=table;
		
		addButton.clicked.connect(this, "addRow()");
		removeButton.clicked.connect(this, "removeRow()");
		table.itemSelectionChanged.connect(this,"enableRemoveRow()");
		
	}
	
	public abstract void addRow();
	
	public void removeRow(){
		int erasedRow;

		erasedRow=table.selectedItems().get(0).row();

//		System.out.println("Devo rimuovere "+table.item(erasedRow,0).text());
		
		removeFromModel(table.item(erasedRow,0).text());
		
		for(int i=erasedRow;i<table.rowCount();i++){
			for(int j=0;j<table.columnCount();j++){
				table.setItem(i, j, table.takeItem(i+1,j));
			}
		}
		
		table.setRowCount(table.rowCount()-1);
		table.clearSelection();
		table.setCurrentCell(table.rowCount(), 0);
		removeButton.setEnabled(false);
		
	}
	
	protected abstract void removeFromModel(String item);

	public void enableRemoveRow(){
		removeButton.setEnabled(table.selectedItems().size()!=0);
	}

}
